import json
import os

# 定义根目录
os.chdir('..')
root_path = os.getcwd()
# print(root_path)


class TransferData:
    def __init__(self):
        # 获取类别字典
        self.label_dict = json.load(open(os.path.join(root_path, 'data/labels.json'), encoding='utf-8'))
        self.seq_tag_dict = json.load(open(os.path.join(root_path, 'data/tag2id.json'), encoding='utf-8'))
        # 定义路径
        self.origin_path = os.path.join(root_path,'data_origin')
        self.train_filepath = os.path.join(root_path,'data/train.txt')

    def transfer(self):
        # 保存转换后的结果
        with open(self.train_filepath,mode='w',encoding='utf-8') as ft:
            #遍历所有文件
            for root,dirs,files in os.walk(self.origin_path):
                #遍历每个files
                for file in files:
                    # 得到所有文字路径
                    file_path = os.path.join(root,file)
                    # 过滤所有非original的文件
                    if 'original' not in file_path:
                        continue
                    # 得到对应标签文件
                    label_file_path = file_path.replace('.txtoriginal','')
                    res_dict = self.read_label_text(label_file_path)
                    # print(res_dict)
                    with open(file_path,mode='r',encoding='utf-8') as ff:
                        content = ff.read()
                        for index,char in enumerate(content):
                            tag = res_dict.get(index,'O')
                            ft.write(char+'\t'+tag+'\n')

        print('操作完毕！！！！')

    def read_label_text(self,path):
        # print(path)
        res_dict = {}
        with open(path,mode='r',encoding='utf-8') as fl:
            lines = fl.readlines()
        for line in lines:
            line = line.strip().split('\t')
            # print(line)
            start = int(line[1])
            end = int(line[2])
            label = line[3]
            label_english = self.label_dict.get(label)
            for i in range(start,end+1):
                if i == start:
                    tag = "B-" + label_english
                else:
                    tag = "I-" + label_english
                res_dict[i] = tag
        return res_dict

if __name__ == "__main__":
    data = TransferData()
    data.transfer()
    # print(data.label_dict)
    # print(data.seq_tag_dict)
